package br.com.dataphonebr.service;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public abstract class GenericAdapterService<Entity> extends BaseAdapter {
	
	private List<Entity> list;
	private Cursor cursor;
	private int dataImage;
	
	public GenericAdapterService(List<Entity> list) {
		this.list = new ArrayList<Entity>(list);
	}

	protected abstract Entity cursorToEntity();
	
	public void cursorToList(){
		if (getCursor() != null){
			setList(new ArrayList<Entity>());
			if (getCursor().moveToFirst()) {
				do {
					Entity entity = cursorToEntity();
					this.addItem(entity);
					} while (getCursor().moveToNext());
				}
			
			if (!getCursor().isClosed()) {
				getCursor().close();
			}
		}
	}

	
	@Override
	public int getCount() {
		if (list != null)
			return list.size();
		return 0;
	}

	@Override
	public Object getItem(int arg0) {
		if (list != null)
			return list.get(arg0);
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	public void addItem(Entity entity) {
		list.add(entity);
	}

	public void setCursor(Cursor cursor) {
		this.cursor = cursor;
	}
	
	public Cursor getCursor() {
		return cursor;
	}
	
	public void setList(List<Entity> list) {
		this.list = list;
	}
	
	public List<Entity> getList(){
		return list;
	}
	
	protected TextView getTextView(int id, View view){
		TextView textView = (TextView)view.findViewById(id);
		return textView;
	}

	protected ImageView getImageView(int id, View view){
		ImageView imgView = (ImageView)view.findViewById(id);
		return imgView;
	}

	public View getView(int index, View view, ViewGroup parent, int layout) {
		if (view == null){
			LayoutInflater inflater = LayoutInflater.from(parent.getContext());
			view = inflater.inflate(layout, parent, false);
		}
		return view;
	}
	
	public int getDataImage() {
		return dataImage;
	}
	
	public void setDataImage(int dataImage) {
		this.dataImage = dataImage;
	}

}
